import React, { useState, forwardRef, useImperativeHandle } from 'react';
import { Modal, Spin, Form, Input, message } from 'antd';
import UserPhoto from '@/pages/common/UserPhoto';
import { getUserId, userUpdate } from '@/services/system/user';
import { useModel } from 'umi';

// 定义传参
interface UpdateUserInfoParams {}

/**
 * 个人中心
 *
 * @author zhangby
 * @date 29/9/20 5:03 pm
 */
const UpdateUserInfo: React.FC<UpdateUserInfoParams> = (props, ref) => {
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const { initialState } = useModel('@@initialState');

  const [form] = Form.useForm();

  useImperativeHandle(ref, () => ({
    // 暴露给父组件的方法
    onPreInit: async () => {
      setVisible(true);
      form.resetFields();

      try {
        setLoading(true);
        // 查询用户详情
        const userData = await getUserId(initialState.currentUser?.userid);
        if (userData.code === '000') {
          form.setFieldsValue(userData.result);
        }
        setLoading(false);
      } catch (e) {
        setLoading(false);
      }
    },
  }));

  // 提交
  const onSubmit = () => {
    form.validateFields().then(async (values) => {
      console.log(values);
      try {
        setLoading(true);
        const params = { ...values };
        const data = await userUpdate({ ...params, id: initialState.currentUser?.userid });
        if (data.code === '000') {
          message.success('编辑用户成功');
          setVisible(false);
          setLoading(false);
        }
      } catch (e) {
        setLoading(false);
      }
    });
  };

  return (
    <>
      <Modal
        title="个人中心"
        visible={visible}
        onOk={onSubmit}
        onCancel={() => setVisible(false)}
        width={600}
      >
        <Spin spinning={loading}>
          <Form {...layout} form={form}>
            <Form.Item name="photo" label="" style={{ marginLeft: 260 }}>
              <UserPhoto isEdit size={60} />
            </Form.Item>
            <Form.Item
              name="name"
              label="用户名"
              rules={[{ required: true, message: '用户名不能为空' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item name="mobile" label="联系方式">
              <Input />
            </Form.Item>
            <Form.Item name="email" label="电子邮箱">
              <Input />
            </Form.Item>
          </Form>
        </Spin>
      </Modal>
    </>
  );
};

const layout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 7 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
  },
};

// @ts-ignore
export default forwardRef(UpdateUserInfo);
